package com.zy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Configuration
public class UpFileConfig {
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver mu = new CommonsMultipartResolver();
        mu.setDefaultEncoding("utf-8");
        //一次请求最多是100MB
        mu.setMaxUploadSize(1024 * 1024 * 100);
        //一个请求一个文件最多是10MB
        mu.setMaxUploadSizePerFile(1024 * 1024 * 10);
        mu.setResolveLazily(true);
        //resolveLazily：延迟解析，默认为false--立即解析multipart request;
        //defaultEncoding：解析请求的默认字符编码 ; 默认值为"ISO-8859-1"。通常设置为"UTF-8";
        //maxUploadSize:文件上传最大值; 默认值为 -1(表示没有限制);
        //maxUploadSizePerFile:每个文件上传最大值;默认值为 -1(表示没有限制);
        //maxInMemorySize:存储在内存的最大值;默认值为10240B(10KB);
        //uploadTempDir:上传文件的临时目录;默认值为WEB应用程序的临时目录;
        return mu;
    }

    //@Bean
    public HandlerExceptionResolver exceptionResolver() {
        HandlerExceptionResolver resolver = (request, response, handler, ex) -> {
            if (ex instanceof MaxUploadSizeExceededException) {
                long maxSize = ((MaxUploadSizeExceededException) ex).getMaxUploadSize();
                System.out.println("上传文件太大，不能超过" + maxSize / 1024 + "k"); // 打印错误信息
                request.setAttribute("msg", "上传文件太大，不能超过" + maxSize / 1024 + "k");
                return new ModelAndView("forward:/ustate");
            }

            //request.setAttribute("msg", "上传文件太大，"+ex.getMessage());
            return new ModelAndView("forward:/ustate");
            //return new ModelAndView("redirect:/ustate");
        };
        return resolver;
    }
}
